<template>
  <view style="display: flex; flex-direction: column; align-items: center; justify-content: center; width: 750rpx; margin-top: 40px">
    <swiper style="width: 750rpx; height: 190px; margin-top: 10px" :current="curIndex" @change="onSwiperChange">
      <swiper-item class="swiper-item">
        <mxp-form
          ref="mxpPassdFormRef"
          itemLabelPosition="top"
          itemErrorMode="label"
          :model="passdForm"
          :fromBorderColor="false"
          :rules="passdRules"
          :cusStyle="{ width: '690rpx' }"
        >
          <mxp-form-item :borderColor="false" labelWidth="0px" label="账号" prop="username" :cusStyle="{ marginBottom: `5px` }">
            <mxp-input-number
              v-model="passdForm.username"
              background="#ffffff"
              placeholder="请输入手机号"
              :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
              :maxlength="11"
              :returnString="true"
              :inputStyle="{ height: '48px', padding: '0px 0px' }"
              verify="add_int_or_zero"
            ></mxp-input-number>
          </mxp-form-item>
          <mxp-form-item :borderColor="false" labelWidth="0px" prop="password" label="密码">
            <mxp-input
              v-model="passdForm.password"
              placeholder="请输入密码"
              :password="true"
              background="#ffffff"
              :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
              :inputStyle="{ height: '48px', padding: '0px 0px' }"
              :maxlength="20"
            ></mxp-input>
          </mxp-form-item>
        </mxp-form>
      </swiper-item>
      <swiper-item class="swiper-item">
        <mxp-form
          ref="mxpSmsCodeFormRef"
          itemErrorMode="label"
          :model="smsCodeForm"
          :fromBorderColor="false"
          itemLabelPosition="top"
          :rules="codeRules"
          :cusStyle="{ width: '690rpx' }"
        >
          <mxp-form-item :borderColor="false" labelWidth="0px" label="手机号" prop="phone" :cusStyle="{ marginBottom: `5px` }">
            <mxp-input-number
              v-model="smsCodeForm.phone"
              background="#ffffff"
              placeholder="请输入手机号"
              :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
              :maxlength="11"
              :returnString="true"
              :inputStyle="{ height: '48px', padding: '0px 0px' }"
              verify="add_int_or_zero"
            ></mxp-input-number>
          </mxp-form-item>
          <mxp-form-item :borderColor="false" labelWidth="0px" prop="smsCode" label="验证码">
            <mxp-input
              v-model="smsCodeForm.smsCode"
              background="#ffffff"
              placeholder="请输入验证码"
              :cusStyle="{ borderRadius: `10px`, padding: '0px 15px' }"
              :inputStyle="{ height: '48px', padding: '0px 0px' }"
              type="number"
              :maxlength="6"
            >
              <template #suffix>
                <mxp-count-down-button ref="mxpCountDownButtonRef" :seconds="60" :cusStyle="{ height: '48px' }" @click="sendAuthCode"></mxp-count-down-button>
              </template>
            </mxp-input>
          </mxp-form-item>
        </mxp-form>
      </swiper-item>
    </swiper>
    <view class="user-action-box">
      <mxp-button text="忘记密码" font-size="14px" :color="defThemeColor.text3" :isTextButton="true" @click="openFindPassdClick"></mxp-button>
      <mxp-button :text="curIndex === 0 ? '短信登录' : '密码登录'" font-size="14px" :isTextButton="true" @click="headerCutLoginType"></mxp-button>
    </view>
    <view
      style="
        box-sizing: border-box;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        width: 100%;
        padding: 0 30rpx;
        margin-top: 40px;
        margin-bottom: 20px;
      "
    >
      <mxp-radio v-model:checked="isAgree" labelSize="14px" label="我已阅读并同意" iconSize="18px"></mxp-radio>
      <text style="font-size: 14px; line-height: 14px; color: #8e4c00" @click="openPrivacyAgreementClick">《隐私政策》</text>
    </view>
    <mxp-button
      text="登 录"
      font-size="18px"
      :background="defThemeColor.buttonColor"
      :bold="true"
      :loading="loading"
      :disabled="loading"
      :cusStyle="{ height: '48px', width: '690rpx', maxWidth: '400px' }"
      @click="onLogin"
    ></mxp-button>
    <view style="padding: 6px 10px; margin-top: 15px">
      <text style="margin-right: 8px; font-size: 14px" :style="{ color: defThemeColor.text3 }">还没有账号?</text>
      <mxp-button text="立即注册" font-size="14px" :isTextButton="true" @click="registerUserClick"></mxp-button>
    </view>
    <mxp-toast ref="mxpToastRef" :customNav="true"></mxp-toast>
  </view>
</template>

<script setup lang="ts">
  import { computed, onBeforeMount, ref, shallowReactive } from 'vue';
  import MxpToast from '@/mxp-ui/mxp-toast/mxp-toast.vue';
  import MxpButton from '@/mxp-ui/mxp-button/mxp-button.vue';
  import MxpFormItem from '@/mxp-ui/mxp-form-item/mxp-form-item.vue';
  import MxpCountDownButton from '@/mxp-ui/mxp-count-down-button/mxp-count-down-button.vue';
  import MxpRadio from '@/mxp-ui/mxp-radio/mxp-radio.vue';
  import MxpInput from '@/mxp-ui/mxp-input/mxp-input.vue';
  import MxpInputNumber from '@/mxp-ui/mxp-input-number/mxp-input-number.vue';
  import { SmsType, passdLoginAxios, sendAuthCodeByPhoneAxios, smsLoginAxios } from '@/api/account';
  import { useAppStore } from '@/pinia/app';
  import { verifyTel } from '@/mxp-ui/mxp-tool/utils/verify';
  import { setLoginInfo } from '../util';
  import MxpForm, { type $Rules } from '@/mxp-ui/mxp-form/mxp-form.vue';
  import type { SwiperOnChangeEvent } from 'mxp-uni-types';
  import { defThemeColor } from '@/mxp-ui/mxp-tool/theme/theme';

  const mxpPassdFormRef = ref<InstanceType<typeof MxpForm> | null>(null);
  const mxpSmsCodeFormRef = ref<InstanceType<typeof MxpForm> | null>(null);
  const mxpCountDownButtonRef = ref<InstanceType<typeof MxpCountDownButton> | null>(null);
  const mxpToastRef = ref<InstanceType<typeof MxpToast> | null>(null);

  /** 当前 swiper */
  const curIndex = ref(0);
  /** 是否同意协议 */
  const isAgree = ref(false);

  const appStore = useAppStore();
  const loading = computed(() => appStore.isLoginLoading);
  const passdForm = shallowReactive({
    username: '',
    password: '',
  });
  const smsCodeForm = shallowReactive({
    phone: '',
    smsCode: '',
  });

  onBeforeMount((op?: { phone?: string }) => {
    if (verifyTel(op?.phone || '')) {
      passdForm.username = op!.phone!;
      smsCodeForm.phone = op!.phone!;
    } else if (import.meta.env.DEV) {
      passdForm.username = '15870433234';
      smsCodeForm.phone = '15870433234';
      passdForm.password = 'qw123321';
    }
  });

  const passdRules: $Rules = {
    username: [
      { type: 'string', required: true, message: '请输入账号', trigger: ['blur', 'change'] },
      { type: 'string', len: 11, message: ' 账号不合法', trigger: ['blur', 'change'] },
    ],
    password: [{ type: 'string', required: true, message: '请输入密码', trigger: ['blur', 'change'] }],
  };
  const codeRules: $Rules = {
    phone: [
      { type: 'string', required: true, message: '请输入账号', trigger: ['blur', 'change'] },
      { type: 'string', len: 11, message: ' 账号不合法', trigger: ['blur', 'change'] },
    ],
    smsCode: [
      { type: 'string', required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
      { type: 'string', len: 6, message: '验证码长度为 6 位', trigger: ['blur', 'change'] },
    ],
  };

  /**
   * 切换登录方式
   */
  function headerCutLoginType() {
    curIndex.value = curIndex.value === 0 ? 1 : 0;
  }
  /**
   * swiper发生变化
   */
  function onSwiperChange(event: SwiperOnChangeEvent) {
    curIndex.value = event.detail.current;
  }

  /**
   * 获取验证码
   */
  async function sendAuthCode() {
    try {
      await mxpSmsCodeFormRef.value!.validateField('phone');
      mxpCountDownButtonRef.value?.setLoadState(true);
      await sendAuthCodeByPhoneAxios(SmsType.AppSMSLogin, smsCodeForm.phone);
      mxpCountDownButtonRef.value?.setLoadState(false);
      mxpCountDownButtonRef.value?.start(); // 开始倒计时
    } catch (e) {
      mxpCountDownButtonRef.value?.setLoadState(false);
    }
  }

  /**
   * 登录
   */
  async function onLogin() {
    if (isAgree.value) {
      try {
        if (curIndex.value === 0) {
          await mxpPassdFormRef.value?.validate();
        } else {
          await mxpSmsCodeFormRef.value?.validate();
        }
        appStore.setIsLoginLoging(true);
        let res = undefined;
        if (curIndex.value === 0) {
          res = await passdLoginAxios({ username: passdForm.username, password: passdForm.password });
        } else {
          res = await smsLoginAxios({ phone: smsCodeForm.phone, smsCode: smsCodeForm.smsCode });
        }
        // 设置token，获取用户信息和基础信息
        await setLoginInfo(res.data);
        appStore.setIsLoginLoging(false);
      } catch (err) {
        console.log('err====', err);
        appStore.setIsLoginLoging(false);
        mxpToastRef.value?.showError(Array.isArray(err) && err[0] && err[0].message ? err[0].message : err.msg || '登录失败,-BD0002');
      }
    } else {
      mxpToastRef.value?.showWarning('请阅读并同意《隐私政策》');
    }
  }

  /** 打开隐私政策 */
  function openPrivacyAgreementClick() {
    uni.navigateTo({ url: '/pages/account/privacy-agreement/privacy-agreement' });
  }

  /** 找回密码 */
  function openFindPassdClick() {
    const phone = curIndex.value === 0 ? passdForm.username : smsCodeForm.phone || '';
    uni.navigateTo({ url: `/pages/account/find-password/find-password?phone=${verifyTel(phone) ? phone : ''}` });
  }

  /** 注册用户 */
  function registerUserClick() {
    const phone = curIndex.value === 0 ? passdForm.username : smsCodeForm.phone || '';
    uni.navigateTo({ url: `/pages/account/register/register?phone=${verifyTel(phone) ? phone : ''}` });
  }
</script>

<style scoped lang="scss">
  .swiper-item {
    box-sizing: border-box;
    width: 750rpx;
    height: 190px;
    padding: 0 30rpx;
  }

  .service-view {
    position: fixed;
    bottom: 40px;
    left: 0;
    display: flex;
    flex: 1;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    width: 690rpx;
    margin-top: 10px;
  }

  .user-action-box {
    box-sizing: content-box;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 690rpx;
    padding: 0 30rpx;
    margin-top: 10px;

    .action-box {
      padding: 2px 0;

      .text {
        font-size: 14px;
      }
    }
  }
</style>
